import React, { useState, useEffect, useRef } from 'react';
import { Card, Button, Table, Modal, message, FormInstance } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { reqUsers, AxiosResponse, reqDeleteUser, reqAddUserInfo, reqUpdateUserInfo } from '../../api';
import formatTime from '../../utils/date';
import UserForm from './UserForm';

type UserName = '_id' | 'username' | 'password' | 'phone' | 'email' | 'role_id' | 'create_time';
type UserInfo = Record<UserName, string> & { __v: 0 };
type Column = {
    title: string;
    dataIndex: string;
    render?: (timeOrUser: React.Key | UserInfo) => string | React.ReactNode;
};

type RoleInfo = {
    menus: string[];
    _id: string;
    name: string;
    auth_time: number;
    auth_name: string;
    create_time: number;
}

// 用户路由组件
const User: React.FC = () => {
    const [isLoading] = useState<boolean>(false);
    const [isShow, setShowModal] = useState<boolean>(false);
    const [users, setUsers] = useState<UserInfo[]>([]);
    const [roles, setRoles] = useState<RoleInfo[]>([]);
    const handleShowModal = (): void => {
        updateUserRef.current = null;
        setShowModal(true);
    }
    const onCancel = (): void => setShowModal(false);
    const addUserRef = useRef<FormInstance | null>(null);
    const updateUserRef = useRef<UserInfo | null>(null);
    const deleteUser = (user: UserInfo): void => {
        Modal.confirm({
            title: `确认删除${user.username}吗?`,
            icon: <ExclamationCircleOutlined />,
            async onOk(): Promise<void> {
                const { data }: AxiosResponse<{
                    status: 0 | 1;
                }> = await reqDeleteUser(user._id);
                if (data.status === 0) {
                    message.success('删除用户成功+_+');
                    getAsyncUsers();
                    return;
                }
                message.error('删除用户失败T_T');
            },
            okText: '确定',
            cancelText: '取消'
        });
    };
    const addOrUpadte = async (): Promise<void> => {
        const user: any = addUserRef.current!.getFieldsValue();
        const isEmptyInput: boolean = Object.values(user).some(v => !v);
        if (isEmptyInput) {
            message.warning('其中有没输入的内容');
            return;
        }
        const isUpdate = !!updateUserRef.current;
        if (isUpdate) {
            user._id = updateUserRef.current!._id;
        }
        const requset = user._id ? reqUpdateUserInfo(user) : reqAddUserInfo(user);
        const { data }: AxiosResponse<{
            status: 0;
            data: any;
        }> = await requset;
        const msg: string = `${isUpdate ? '更新' : '添加'}用户`;
        if (data.status === 0) {
            message.success(`${msg}成功`);
            setShowModal(false);
            getAsyncUsers();
            return;
        }
        message.error(`${msg}失败`);
    };
    const showUpdate = (user: UserInfo) => {
        updateUserRef.current = user;
        setShowModal(true);
    };
    const getAsyncUsers = async (): Promise<void> => {
        const { data }: AxiosResponse<{
            status: 0,
            data: {
                users: UserInfo[];
                roles: RoleInfo[];
            }
        }> = await reqUsers();
        if (data.status === 0) {
            const { users, roles } = data.data;
            setUsers(users);
            setRoles(roles);
        }
    };
    const title: React.ReactNode = <Button type="primary" onClick={handleShowModal}>创建用户</Button>;
    const columns: Column[] = [
        {
            title: '用户名',
            dataIndex: 'username'
        },
        {
            title: '邮箱',
            dataIndex: 'email'
        },
        {
            title: '电话',
            dataIndex: 'phone'
        },
        {
            title: '注册时间',
            dataIndex: 'create_titme',
            render(time) {
                return typeof time === 'number' ? formatTime(new Date(time)) : time;
            }
        },
        {
            title: '所属角色',
            dataIndex: 'role_id',
            render(role_id) {
                const { name }: RoleInfo | { name: string } = roles.find(({ _id }) => _id === role_id) ?? { name: '' };
                return name;
            }
        },
        {
            title: '操作',
            dataIndex: '',
            render(user) {
                return (
                    <span>
                        <Button type="link" onClick={() => showUpdate(user as UserInfo)}>修改</Button>
                        <Button type="link" onClick={() => deleteUser(user as UserInfo)}>删除</Button>
                    </span>
                );
            }
        }
    ];
    useEffect(() => {
        getAsyncUsers();
    }, []);
    return (
        <Card title={title}>
            <Table
                bordered
                rowKey="_id"
                loading={isLoading}
                dataSource={users}
                columns={columns}
                pagination={{
                    defaultPageSize: 5,
                    showQuickJumper: true
                }}
            />
            <Modal destroyOnClose title={updateUserRef.current ? '更新用户' : '创建用户'} visible={isShow} onOk={addOrUpadte} onCancel={onCancel} okText="确定" cancelText="取消">
                <UserForm addUserRef={addUserRef} roles={roles} user={updateUserRef.current} />
            </Modal>
        </Card>
    );
};

export default User;